

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;light&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/me/title.jpg">
  <link rel="icon" type="image/png" href="/img/me/title.jpg">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="你要悄悄学web，然后惊艳所有人">
  <meta name="author" content="yxfan">
  <meta name="keywords" content="">
  <title>TypeScript中的泛型 - yxfan</title>

  <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/highlight.js@10.4.0/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","version":"1.8.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3","placement":"right","visible":"always","Option":"§ |","icon":"#"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":20},"lazyload":{"enable":true,"onlypost":false},"web_analytics":{"enable":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"AGrJP3tUCktoWpoiRigqj3zy-gzGzoHsz","app_key":"r0u61FlVNs3yvXwGYocWG3qm","server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>yxfan</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/background/lu_bule.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="TypeScript中的泛型">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2019-12-24 21:52" pubdate>
        2019年12月24日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      813 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      11
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">TypeScript中的泛型</h1>
            
            <div class="markdown-body">
              <h3 id="什么是泛型"><a href="#什么是泛型" class="headerlink" title="什么是泛型"></a>什么是泛型</h3><p>软件工程中，我们不仅要创建一致的定义良好的API，同时也要考虑可重用性。 组件不仅能够支持当前的数据类型，同时也能支持未来的数据类型，这在创建大型系统时为你提供了十分灵活的功能。</p>
<p>在像C#和Java这样的语言中，可以使用泛型来创建可重用的组件，一个组件可以支持多种类型的数据。 这样用户就可以以自己的数据类型来使用组件。</p>
<p>通俗理解：泛型就是解决 类 接口 方法的复用性、以及对不特定数据类型的支持(类型校验)</p>
<p>我们用 T 来表示泛型，当然也可以用其他字母表示</p>
<h3 id="泛型类"><a href="#泛型类" class="headerlink" title="泛型类"></a>泛型类</h3><p>我们举一个例子，找数组中最小的元素，它可以是number，也可以是string</p>
<div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MinClas</span>&lt;<span class="hljs-title">T</span>&gt;</span>&#123;
    public list:T[]=[];
    add(value:T):<span class="hljs-keyword">void</span>&#123;
        <span class="hljs-built_in">this</span>.list.push(value);
    &#125;
    min():T&#123;        
        <span class="hljs-keyword">var</span> minNum=<span class="hljs-built_in">this</span>.list[<span class="hljs-number">0</span>];
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i=<span class="hljs-number">0</span>;i&lt;<span class="hljs-built_in">this</span>.list.length;i++)&#123;
            <span class="hljs-keyword">if</span>(minNum&gt;<span class="hljs-built_in">this</span>.list[i])&#123;
                minNum=<span class="hljs-built_in">this</span>.list[i];
            &#125;
        &#125;
        <span class="hljs-keyword">return</span> minNum;
    &#125;
&#125;
<span class="hljs-comment">/*实例化类 并且制定了类的T代表的类型是number*/</span>
<span class="hljs-keyword">var</span> m1=<span class="hljs-keyword">new</span> MinClas&lt;number&gt;();   
m1.add(<span class="hljs-number">11</span>);
m1.add(<span class="hljs-number">3</span>);
m1.add(<span class="hljs-number">2</span>);
alert(m1.min()) <span class="hljs-comment">// 2</span>

<span class="hljs-comment">/*实例化类 并且制定了类的T代表的类型是string*/</span>
<span class="hljs-keyword">var</span> m2=<span class="hljs-keyword">new</span> MinClas&lt;string&gt;();   
m2.add(<span class="hljs-string">&#x27;c&#x27;</span>);
m2.add(<span class="hljs-string">&#x27;a&#x27;</span>);
m2.add(<span class="hljs-string">&#x27;v&#x27;</span>);
alert(m2.min()) <span class="hljs-comment">// &#x27;a&#x27;</span></code></pre></div>
<p>注意：T 表示泛型，它具体指什么类型是调用这个方法的时候决定的</p>
<h3 id="泛型接口"><a href="#泛型接口" class="headerlink" title="泛型接口"></a>泛型接口</h3><p>泛型解决、类、接口、方法的复用性<br>而接口是一种规范的定义，它定义了行为和动作的规范（约束）</p>
<div class="code-wrapper"><pre><code class="hljs javascript"><span class="hljs-comment">//定义一个方法接口</span>
interface ConfigFn&#123;
   &lt;T&gt;(value:T):T;
&#125;
<span class="hljs-keyword">var</span> getData:ConfigFn=<span class="hljs-function"><span class="hljs-keyword">function</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">value:T</span>):<span class="hljs-title">T</span></span>&#123;
  <span class="hljs-keyword">return</span> value;
&#125;
<span class="hljs-comment">//此时给出了泛型的具体类型</span>
getData&lt;string&gt;(<span class="hljs-string">&#x27;张三&#x27;</span>);
getData&lt;string&gt;(<span class="hljs-number">1243</span>);  <span class="hljs-comment">//错误</span></code></pre></div>
<p>当然也可以这样写，两者等效</p>
<div class="code-wrapper"><pre><code class="hljs javascript">interface ConfigFn&lt;T&gt;&#123;
    (value:T):T;
&#125;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">value:T</span>):<span class="hljs-title">T</span></span>&#123;
     <span class="hljs-keyword">return</span> value;
&#125;
<span class="hljs-comment">//此时给出了泛型的具体类型</span>
<span class="hljs-keyword">var</span> myGetData:ConfigFn&lt;string&gt;=getData;     
myGetData(<span class="hljs-string">&#x27;20&#x27;</span>);  <span class="hljs-comment">/*正确*/</span>
myGetData(<span class="hljs-number">20</span>)  <span class="hljs-comment">//错误</span></code></pre></div>
<h3 id="泛型接口和泛型类混合"><a href="#泛型接口和泛型类混合" class="headerlink" title="泛型接口和泛型类混合"></a>泛型接口和泛型类混合</h3><p>注意：要实现泛型接口 这个类也应该是一个泛型类<br>定义一个操作数据库的库  支持 Mysql Mssql  MongoDb：</p>
<div class="code-wrapper"><pre><code class="hljs javascript">interface DBI&lt;T&gt;&#123;
    add(info:T):boolean;
    update(info:T,<span class="hljs-attr">id</span>:number):<span class="hljs-keyword">void</span>;
&#125;
<span class="hljs-comment">//定义一个操作mysql数据库的类       </span>
<span class="hljs-comment">//注意：要实现泛型接口 这个类也应该是一个泛型类</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MysqlDb</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-title">implements</span> <span class="hljs-title">DBI</span>&lt;<span class="hljs-title">T</span>&gt;</span>&#123;
    <span class="hljs-function"><span class="hljs-title">constructor</span>(<span class="hljs-params"></span>)</span>&#123;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;数据库建立连接&#x27;</span>);
    &#125;
    <span class="hljs-comment">//必须实现接口的方法</span>
    add(info: T): boolean &#123;
        <span class="hljs-built_in">console</span>.log(info);
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    &#125;
    <span class="hljs-comment">//必须实现接口的方法    </span>
    update(info: T, <span class="hljs-attr">id</span>: number): <span class="hljs-keyword">void</span> &#123;
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">&quot;Method not implemented.&quot;</span>);
    &#125;
&#125;
<span class="hljs-comment">//操作用户表   定义一个User类和数据表做映射</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span></span>&#123;
    <span class="hljs-attr">username</span>:string | <span class="hljs-literal">undefined</span>;
    password:string | <span class="hljs-literal">undefined</span>;
&#125;
<span class="hljs-keyword">var</span> u=<span class="hljs-keyword">new</span> User();
u.username=<span class="hljs-string">&#x27;张三111&#x27;</span>;
u.password=<span class="hljs-string">&#x27;123456&#x27;</span>;

<span class="hljs-keyword">var</span> oMysql=<span class="hljs-keyword">new</span> MysqlDb&lt;User&gt;(); <span class="hljs-comment">//类作为参数来约束数据传入的类型 </span>
oMysql.add(u);<span class="hljs-comment">//User &#123;username: &quot;张三111&quot;, password: &quot;123456&quot;&#125;</span></code></pre></div>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/TypeScript/">TypeScript</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">转载请注明出处！</p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2019/12/30/DNS%E4%B8%8ECDN/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">DNS与CDN</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2019/12/21/typescript%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">
                        <span class="hidden-mobile">typescript数据类型</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    
  </div>
  

  

  
</footer>

<!-- SCRIPTS -->

  <script  src="https://fastly.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://fastly.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://fastly.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" ></script>
<script  src="https://fastly.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script  src="https://fastly.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js" ></script>



  <script  src="https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://fastly.jsdelivr.net/npm/anchor-js@4.3.0/anchor.min.js" ></script>



  <script defer src="https://fastly.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>


  <script defer src="/js/leancloud.js" ></script>



  <script  src="https://fastly.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "/local-search.xml";
      var inputArea = document.querySelector("#local-search-input");
      inputArea.onclick = function () {
        searchFunc(path, 'local-search-input', 'local-search-result');
        this.onclick = null
      }
    })()
  </script>












  

  

  

  

  

  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>



</body>
</html>
